package com.jstyle.jclife.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.BaseActivity;
import com.jstyle.jclife.daoManager.PathRecordDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.PathRecord;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.view.HeadCircleView;
import com.yalantis.ucrop.UCrop;

import java.text.NumberFormat;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SharePictureFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SharePictureFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_share_photo)
    Button btSharePhoto;

    @BindView(R.id.iv_share_icon)
    ImageView ivShareIcon;
    @BindView(R.id.tv_share_cal)
    TextView tvShareCal;
    @BindView(R.id.tv_exerciseTime)
    TextView tvExerciseTime;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_pace)
    TextView tvPace;
    @BindView(R.id.ll_data)
    LinearLayout llData;
    Unbinder unbinder;
    @BindView(R.id.tv_share_userId)
    TextView tvShareUserId;
    @BindView(R.id.tv_share_time)
    TextView tvShareTime;
    @BindView(R.id.bt_device_name)
    Button btDeviceName;
    @BindView(R.id.iv_share_userIcon)
    ImageView ivShareUserIcon;
    @BindView(R.id.CardView)
    android.support.v7.widget.CardView CardView;
    @BindView(R.id.iv_share_bg)
    ImageView ivShareBg;
    @BindView(R.id.share_bottom)
    RelativeLayout rlShareBottom;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private AlertDialog iconDialog;
    private Uri caremaUri;
    private Uri iconUri;

    public SharePictureFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SharePictureFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SharePictureFragment newInstance(String param1, String param2) {
        SharePictureFragment fragment = new SharePictureFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_share_picture, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {

        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        PathRecord pathRecord = PathRecordDaoManager.getPathRecord(mParam2);
        String distance = pathRecord.getMDistance();
        int exerciseTime = Integer.valueOf(pathRecord.getMDuration());
        String showDistance = ResolveData.getShowDistance(String.valueOf(distance));
        String showPace = ResolveData.getShowPace(getActivity(), pathRecord.getMAveragespeed());
        String cal = pathRecord.getCalString();
        String duration = DateUtil.getSportTime(exerciseTime);
        String calLabel = getString(R.string.cal_laber);
        String paceLabel = ResolveData.getSharePaceLabel(getContext());
        String distanceLabel = ResolveData.getDistanceLabel();
        tvExerciseTime.setText(duration);
        Spannable spannableCal = ScreenUtils.getSpannable(cal + calLabel, cal, 30);
        tvShareCal.setText(spannableCal);
        Spannable spannablePace = ScreenUtils.getSpannable(showPace + paceLabel, paceLabel, 10);
        tvPace.setText(spannablePace);
        Spannable spannableDistance = ScreenUtils.getSpannable(showDistance + distanceLabel, distanceLabel, 10);
        tvDistance.setText(spannableDistance);
        tvShareTime.setText(DateUtil.getShareShowDate(getContext(),mParam2));

        String uid = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid);
        if (userInfo != null) {
            String name = userInfo.getName();
            if (!TextUtils.isEmpty(name)) tvShareUserId.setText(name);
            Uri iconUri = ImageUtils.getIconUri(getActivity(), userInfo.getUserId());
            Bitmap bmHead = ImageUtils.findHeadBitmap(getActivity(), iconUri);
            bmHead = bmHead == null ? BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.share_icon) : bmHead;
            HeadCircleView circleView = new HeadCircleView(bmHead);
            ivShareUserIcon.setImageDrawable(circleView);
        }
        iconUri = ImageUtils.getIconUri(getContext(), "share");
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.bt_share_photo)
    public void onViewClicked() {
        showChangeIconDialog();
    }

    public void openCameraImage(final Uri uri) {
        PermissionsUtil.requestPermissions((BaseActivity) getActivity(), new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, ImageUtils.GET_IMAGE_BY_CAMERA);
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.CAMERA);

    }

    public void openLocalImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, ImageUtils.GET_IMAGE_FROM_PHONE);
    }

    private void showChangeIconDialog() {
        if (iconDialog == null) {
            iconDialog = new AlertDialog.Builder(getContext(), R.style.appalertdialog).setItems(R.array.change_icon, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 1) {
                        caremaUri = ImageUtils.createImagePathUri(getContext());
                        openCameraImage(caremaUri);
                    } else {
                        openLocalImage();
                    }
                }
            }).setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).create();
        }
        iconDialog.show();
        ScreenUtils.setDialogButtonTextColor(iconDialog);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private static final String TAG = "SharePictureFragment";

    public void shareFile() {
        int h = 0;
        int width = CardView.getWidth();
//        for (int j = 0; j < CardView.getChildCount(); j++) {
//            h += CardView.getChildAt(j).getHeight();
//        }
        int ivHeight=ivShareBg.getHeight();
        int bottomHeight=rlShareBottom.getHeight();
        h=ivHeight+bottomHeight;
        final Bitmap bitmap = Bitmap.createBitmap(width, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(getActivity().getResources().getColor(R.color.main_bg_color));
        CardView.draw(canvas);
        final String path = mParam2 + "2.jpg";
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                ScreenUtils.saveShotPic(bitmap, path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                ScreenUtils.shareByPhone(getContext(), path);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        switch (requestCode) {
            case UCrop.REQUEST_CROP:
                setBitMap();
                break;
            case ImageUtils.CROP_IMAGE:
                setBitMap();
                break;
            case ImageUtils.GET_IMAGE_BY_CAMERA:
                cropImage(ivShareBg.getWidth(),
                        ivShareBg.getHeight(), caremaUri, iconUri);
                break;
            case ImageUtils.GET_IMAGE_FROM_PHONE:
                cropImage(ivShareBg.getWidth(),
                        ivShareBg.getHeight(), data.getData(),
                        iconUri);
                break;
            default:
                break;
        }
    }

    private void setBitMap() {

        ImageUtils.getIconUri(getContext(), "share");
        Bitmap bmHead = ImageUtils.findHeadBitmap(getActivity(), iconUri);
        ivShareBg.setImageBitmap(bmHead);
    }

    public static final int GET_IMAGE_BY_CAMERA = 5001;
    public static final int GET_IMAGE_FROM_PHONE = 5002;
    public static final int CROP_IMAGE = 5003;

    public void cropImage(int width, int height, Uri srcUri, Uri targetUri) {
        UCrop.of(srcUri, targetUri)
                .withAspectRatio(1, 1)
                .start(getContext(), this);
        //  Crop.of(srcUri, targetUri).asSquare().start(getContext(),this);
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(srcUri, "image/*");
//        intent.putExtra("crop", "true");
//        if (Build.MANUFACTURER.equals("HUAWEI")) {
//            intent.putExtra("aspectX", 9998);
//            intent.putExtra("aspectY", 9999);
//        } else {
//            intent.putExtra("aspectX", 1);
//            intent.putExtra("aspectY", 1);
//        }
//
//        intent.putExtra("outputX", width);
//        intent.putExtra("outputY", height);
//        intent.putExtra("scale", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
//        // return-data为true时,会直接返回bitmap数据,但是大图裁剪时会出现问题,推荐下面为false时的方式
//        // return-data为false时,不会返回bitmap,但需要指定一个MediaStore.EXTRA_OUTPUT保存图片uri
//        intent.putExtra("return-data", false);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra("noFaceDetection", true); // no face detection
//
//        startActivityForResult(intent, CROP_IMAGE);
    }

}
